from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.forms import UserCreationForm
from myproject.auth.models import User, AbstractUser, Student, Teacher, Institute, StudentForm, TeacherForm, InstituteForm
from myproject.auth.views import index
from myproject.myprofile.views import getUser
from django.contrib.auth import login
import re

def userReg(request):
    email, email_error, userType_error = '', '', ''
    
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        email = request.POST['email']
        
        # VALIDATION
        # 1. Email
        email_error = emailValidation(email)
        
        # 2. Category
        try:
            category = request.POST['user_type']
            userType_error = ''
        except KeyError:
            userType_error = "This field is required."
    
        # 3. USER 
        if form.is_valid() and not userType_error and not email_error:
            # Create and save user
            user = User(username=form.cleaned_data['username'], email=email)
            user.set_password(form.cleaned_data['password2'])                
            user.save()
            user.backend = 'django.contrib.auth.backends.ModelBackend' 
            login(request, user)
            # Create and save abstract_user
            abstract_user = AbstractUser(user=user)
            abstract_user.save()
            # Create and save student/teacher/institute
            if category == 'student':
                Student(abstract_user=abstract_user).save()
                form = StudentForm()
            elif category == 'teacher':
                Teacher(abstract_user=abstract_user).save()
                form = TeacherForm()
            else:
                Institute(abstract_user=abstract_user).save()
                form = InstituteForm()
            return render_to_response('reg/additionalInfo.html', {'form':form, 'category':category}, context_instance=RequestContext(request))
    else:
        form = UserCreationForm()
    return render_to_response('reg/userReg.html', {'form':form, 'email':email, 'email_error':email_error, 'userType_error':userType_error}, context_instance=RequestContext(request))

def emailValidation(email):
    if User.objects.filter(email=email): # this means that the email was found in the db. Error msg needs to be set now
            email_error = "This email addressed is already registered"
    elif not re.match(r'.+@.+[.].+.+', email):
        email_error = "Please enter a valid email address"
    else:
        email_error = '' # no error
    return email_error

def additionalInfo(request):
    currentUser = getUser(request.user, False)
    currentUser.HOF = False
    if currentUser.category == 'student':
        form = StudentForm(request.POST)
        if form.is_valid():
            first_name = request.POST['first_name']
            last_name = request.POST['last_name']
            request.user.first_name = first_name
            request.user.last_name = last_name
            request.user.save()
            
            currentUser.dob = form.cleaned_data['dob']
            currentUser.gender = form.cleaned_data['gender']
            currentUser.experience = form.cleaned_data['experience']
            currentUser.favourite_genre = form.cleaned_data['favourite_genre']
            currentUser.instrument_played = form.cleaned_data['instrument_played']
            currentUser.jamming_style = form.cleaned_data['jamming_style']
            currentUser.category = 'student'
            currentUser.save()
            return index(request)
    elif currentUser.category == 'teacher':
        form = TeacherForm(request.POST)
        if form.is_valid():
            first_name = request.POST['first_name']
            last_name = request.POST['last_name']
            request.user.first_name = first_name
            request.user.last_name = last_name
            request.user.save()
            
            currentUser.dob = form.cleaned_data['dob']
            currentUser.gender = form.cleaned_data['gender']
            currentUser.experience = form.cleaned_data['experience']
            currentUser.favourite_genre = form.cleaned_data['favourite_genre']
            currentUser.instrument_played = form.cleaned_data['instrument_played']
            currentUser.jamming_style = form.cleaned_data['jamming_style']
            currentUser.teaches = form.cleaned_data['teaches']
            currentUser.category = 'teacher'
            currentUser.save()
            return index(request)
    else:
        form = InstituteForm(request.POST)
        if form.is_valid():
            currentUser.about = form.cleaned_data['about']
            currentUser.address = form.cleaned_data['address'] 
            currentUser.open_on = form.cleaned_data['open_on']
            currentUser.open_from = form.cleaned_data['open_from']
            currentUser.open_to = form.cleaned_data['open_to']
            currentUser.category = 'institute'
            currentUser.save()
            return index(request)
    
    return render_to_response('reg/additionalInfo.html', {'form':form}, context_instance=RequestContext(request))